using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using OfficeOpenXml;
using UnityEditor;
using UnityEngine;

namespace Tools.ExcelToJson.Editor
{
    /// <summary>
    /// https://www.cjavapy.com/article/2399/
    /// </summary>
    public class ExcelToJsonWindow : EditorWindow
    {
        [MenuItem("Tools/Json/Excel2Json")]
        public static void ShowMyEditor()
        {
            EditorWindow wnd = GetWindow<ExcelToJsonWindow>();
            wnd.titleContent = new GUIContent("Excel2Json");
        }

        private string _excelFilePath;
        private string[] _tabNames = Array.Empty<string>();
        private ExcelToJsonTabWindow[] _tabWindows = Array.Empty<ExcelToJsonTabWindow>();
        private int _tabIndex;

        private void OnEnable()
        {
            foreach (var tabWindow in _tabWindows) 
                tabWindow.OnEnable();
        }

        private void OnGUI()
        {
            EditorGUILayout.HelpBox("1.默认生成所有字段为string的json\n" +
                                    "2.若要生成指定数据结构的json，下拉列表选择对应类型\n" +
                                    "3.指定类型过滤采用的策略是通过类名，以JsonData结尾。可以考虑通过集成的方式定义出该结构。" +
                                    "例如原始数据结构类型为MyData，定义MyJsonData : MyData，MyJsonData则会进入下拉列表", MessageType.Info);

            GUILayout.Space(4);
            GUILayout.BeginHorizontal();
            _excelFilePath = EditorGUILayout.TextField("Excel", _excelFilePath);
            if (GUILayout.Button("选择", GUILayout.Width(60))) 
                OnSelectFile();
            if (GUILayout.Button("打开", GUILayout.Width(60))) 
                OnOpenFile(_excelFilePath);
            GUILayout.EndHorizontal();

            OnTabWindow();
        }

        private void OnSelectFile()
        {
            var path = EditorUtility.OpenFilePanel("Excel", "", "xlsx");
            if (!string.IsNullOrEmpty(path))
                _excelFilePath = path;
        }

        private void OnOpenFile(string excelFilePath)
        {
            using (var excelPack = EPPlusUtils.Open(excelFilePath))
            {
                var worksheets = excelPack.Workbook.Worksheets;
                _tabNames = new string[worksheets.Count];
                _tabWindows = new ExcelToJsonTabWindow[worksheets.Count];
                _tabIndex = 0;
                for (var i = 0; i < worksheets.Count; i++)
                {
                    var worksheet = worksheets[i];
                    _tabNames[i] = worksheet.Name;
                    _tabWindows[i] = new ExcelToJsonTabWindow(worksheet.Name, worksheet.ExcelSheetToJson(true));
                }
            }
        }

        private void OnTabWindow()
        {
            if (_tabNames.Length > 0)
            {
                _tabIndex = GUILayout.Toolbar(_tabIndex, _tabNames);
                _tabWindows[_tabIndex].OnGUI();
            }
        }
    }
}